/**
 * Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are NOT permitted except as agreed by
 * iAuto (Shanghai) Co., Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

import React from 'react';
import IAutoTable from '@/components/soa/IAutoTable';
import { PlusOutlined } from '@ant-design/icons';
import { useAntdTable, useRequest } from 'ahooks';
import IAutoSearch from '@/components/soa/IAutoSearch';
import IAutoPage from '@/components/soa/IAutoPage';

import {
  Form,
  Input,
  InputNumber,
  Select,
  Row,
  Space,
  Modal,
  Col,
  message,
  Popconfirm,
  TableColumnsType,
} from 'antd';

import { useState, useEffect, useMemo } from 'react';
import { getDateTime, refreshOrGoPrePage } from '@/utils/soa/utils';
import {
  categoryCreate,
  categoryDelete,
  categoryEdit,
  categoryStatusEdit,
  getCategoryList,
} from '@/services/soa/sceneCategoty';
import { getSeriesModelList } from '@/services/soa/sceneOfficial';
import { ICategoryListItem, IStatus } from '@/types/sceneCategory';
import IAutoStatus from '@/components/soa/IAutoStatus';
import { DELETE_MESSAGE } from '@/utils/soa/constant';
import { scenesCategoryReg } from '@/utils/soa/check';
// import IAutoSearchInput from '@/components/soa/IAutoSearchInput';
import IAutoButton from '@/components/soa/IAutoButton';

const { Option } = Select;
const { Item, useForm } = Form;
const { TextArea } = Input;

export default (props: any) => {
  const {
    location: { pathname },
  } = props;
  const [form] = useForm();
  const [addForm] = useForm();
  const [open, setOpen] = useState(false);
  const [add, setAdd] = useState(false);
  const [record, setRecord] = useState<ICategoryListItem>();
  const [status, setStatus] = useState(2);
  // 当添加修改表单关闭的时候清空表单并且关闭抽屉
  const seriesModelRequest = useRequest(getSeriesModelList);
  const seriesModelList = useMemo(() => seriesModelRequest?.data?.data ?? [], [seriesModelRequest]);

  const onclose = () => {
    addForm.resetFields();
    setOpen(false);
  };

  const { tableProps, search, refresh, params } = useAntdTable(getCategoryList, {
    form,
    manual: true,
  });
  const { submit } = search;

  useEffect(() => {
    seriesModelRequest.run();
  }, []);
  useEffect(() => {
    if (seriesModelList.length) {
      form?.setFieldValue?.('seriesCode', seriesModelList[0].code);
    }
  }, [seriesModelList]);

  const seriesCode = Form.useWatch('seriesCode', form);
  useEffect(() => {
    if (seriesCode) {
      submit();
    }
  }, [seriesCode]);

  //  新增
  const categoryCreateRes = useRequest(categoryCreate, {
    manual: true,
    onSuccess: response => {
      if (response.statusCode === '0') {
        message.success('保存成功');
        onclose();
        refresh();
      }
    },
  });
  //  修改
  const categoryEditRes = useRequest(categoryEdit, {
    manual: true,
    onSuccess: response => {
      if (response.statusCode === '0') {
        message.success('保存成功');
        onclose();
        refresh();
      }
    },
  });

  // 停用与启用调接口
  const categoryStatusEditRes = useRequest(categoryStatusEdit, {
    manual: true,
    onSuccess: (response, status) => {
      if (response.statusCode === '0') {
        message.success(status[0] === 1 ? '停用成功' : '启用成功');
        refresh();
      }
    },
  });

  // 删除调接口
  const categoryDeleteRes = useRequest(categoryDelete, {
    manual: true,
    onSuccess: response => {
      if (response.statusCode === '0') {
        message.success('删除成功');
        refreshOrGoPrePage({ tableProps, params });
      }
    },
  });

  //表单提交
  const onFinish = (values: ICategoryListItem) => {
    const seriesName = seriesModelList.find(item => item.code === values.seriesCode)?.name ?? '';
    if (add) {
      categoryCreateRes.run({
        ...values,
        seriesName,
        status: 2,
      });
    } else {
      categoryEditRes.run(
        {
          ...values,
          seriesName,
          status: status,
        },
        record!.id,
      );
    }
  };

  //列表名称
  const columns: TableColumnsType<ICategoryListItem> = [
    {
      title: '编号',
      dataIndex: 'index',
      width: 50,
    },
    {
      title: '分类名称',
      dataIndex: 'name',
      width: 100,
      ellipsis: true,
    },
    {
      title: '描述',
      dataIndex: 'description',
      width: 180,
      ellipsis: true,
    },
    {
      title: '排序号',
      dataIndex: 'weight',
      width: 80,
    },
    {
      title: '状态',
      width: 100,
      dataIndex: 'status',
      render: text => IAutoStatus(text),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 180,
      render: text => getDateTime(text),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 130,
      render: (_, record) => {
        if (record.name !== '用户共创') {
          return (
            <Space>
              <Popconfirm
                title={`请确认是否${record.status === 0 ? '停用' : '启用'}?`}
                onConfirm={() => {
                  categoryStatusEditRes.run(Number(!record.status) as IStatus, record.id);
                }}
              >
                <IAutoButton pathname={pathname} auth={'category_doEnable'}>
                  {record.status === 0 ? '停用' : '启用'}
                </IAutoButton>
              </Popconfirm>

              <IAutoButton
                onClick={() => {
                  addForm.setFieldsValue({
                    name: record.name,
                    seriesCode: record.seriesCode,
                    description: record.description,
                    weight: record.weight,
                    status: record.status,
                  });
                  setRecord(record);
                  setStatus(record.status);
                  setOpen(true);
                  setAdd(false);
                }}
                disabled={record.status === 0}
                pathname={pathname}
                auth={'category_doEdit'}
              >
                修改
              </IAutoButton>

              <Popconfirm
                title={DELETE_MESSAGE}
                onConfirm={() => {
                  categoryDeleteRes.run(record.id);
                }}
              >
                <IAutoButton
                  pathname={pathname}
                  auth={'category_doDel'}
                  disabled={record.status === 0}
                >
                  删除
                </IAutoButton>
              </Popconfirm>
            </Space>
          );
        }
      },
    },
  ];
  return (
    <div>
      <IAutoSearch>
        <Row align={'middle'}>
          <Col flex={'none'}>
            <Form form={form} layout={'inline'}>
              <Item
                label="车系"
                required
                name="seriesCode"
                rules={[{ required: true, message: '必须选择车系' }]}
              >
                <Select style={{ width: '200px' }} placeholder={'请选择车系'}>
                  {seriesModelList?.map?.((obj: any) => (
                    <Option value={obj.code} key={obj.code}>
                      {obj.name}
                    </Option>
                  ))}
                </Select>
              </Item>
              <Item name="name">
                {/*<IAutoSearchInput*/}
                {/*  style={{ width: 400 }}*/}
                {/*  submit={submit}*/}
                {/*  placeholder="请输入分类名称进行检索"*/}
                {/*/>*/}
                <Input
                  style={{ width: 400 }}
                  placeholder="请输入分类名称进行检索"
                  allowClear
                  maxLength={20}
                />
              </Item>
            </Form>
          </Col>
          <Col flex={'auto'}>
            <Row justify={'end'}>
              <Col>
                <Space>
                  <IAutoButton
                    buttonType={'form'}
                    type={undefined}
                    pathname={pathname}
                    auth={'category_doSearch'}
                    onClick={submit}
                  >
                    查询
                  </IAutoButton>
                  <IAutoButton
                    size="small"
                    buttonType={'form'}
                    icon={<PlusOutlined />}
                    type={'primary'}
                    onClick={() => {
                      setOpen(true);
                      setAdd(true);
                    }}
                    pathname={pathname}
                    auth={'category_doAdd'}
                  >
                    新增
                  </IAutoButton>
                </Space>
              </Col>
            </Row>
          </Col>
        </Row>
      </IAutoSearch>
      <IAutoPage>
        <IAutoTable columns={columns} tableProps={tableProps} size="small" />
      </IAutoPage>
      <Modal
        onCancel={onclose}
        onClose={onclose}
        visible={open}
        width={500}
        title={add ? '新增分类' : '修改分类'}
        onOk={() => addForm.submit()}
      >
        <Form
          name="add"
          form={addForm}
          onFinish={onFinish}
          initialValues={{
            weight: 0,
          }}
        >
          <Form.Item
            name="seriesCode"
            label="车系"
            rules={[
              {
                required: true,
                message: '请选择车系！',
              },
            ]}
          >
            <Select disabled={!add} placeholder={'请选择车系'}>
              {seriesModelList?.map?.((obj: any) => (
                <Option value={obj.code} key={obj.code}>
                  {obj.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="name"
            label="名称"
            rules={[
              {
                required: true,
                // whitespace: true,
                message: '请填写分类名称！',
              },
              {
                pattern: scenesCategoryReg,
                message: '名称需满足中文、英文、数字，长度2~12位',
              },
            ]}
          >
            <Input placeholder={'请输入'} maxLength={12} />
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
            rules={[
              {
                required: true,
                // whitespace: true,
                message: '请输入分类描述！',
              },
            ]}
          >
            <TextArea allowClear placeholder={'请输入描述'} maxLength={128} />
          </Form.Item>
          <Form.Item name="weight" label="排序号">
            <InputNumber min={0} max={999} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
